import React, { useState } from 'react';
import { Form, Input, message, Modal } from 'antd';
import { GlobalFormLayout } from '@/layouts/Form';
import request from '@/utils/request';

const { Search } = Input;

function AddTenantModal({ data = {}, visible, onCancel, form }) {
  const { tenantId, tenantName, tenantCode, httpDataSourceUrlPrefix, accessKey } = data;
  const { getFieldDecorator, validateFields, getFieldValue, setFieldsValue } = form;
  const [loading, setLoading] = useState(false);
  const [accessKeyLoading, setAccessKeyLoading] = useState(false);

  const handleSubmit = () => {
    validateFields((err, data) => {
      if (!err) {
        setLoading(true);
        if (tenantId) {
          data = { ...data, tenantId };
        }
        request
          .post(`/tenant/${tenantId ? 'update' : 'create'}`, { data })
          .then(() => {
            message.success('创建成功');
            onCancel();
          })
          .finally(() => setLoading(false));
      }
    });
  };

  const generateAccessKey = () => {
    setAccessKeyLoading(true);
    request
      .get('/tenant/generateAccessKey')
      .then(({ accessKey }) => setFieldsValue({ accessKey }))
      .finally(() => setAccessKeyLoading(false));
  };

  return (
    <Modal
      title="新增租户"
      width={650}
      onOk={handleSubmit}
      okButtonProps={{ loading }}
      visible={visible}
      onCancel={onCancel}
      destroyOnClose
    >
      <Form {...GlobalFormLayout}>
        <Form.Item label="租户名称">
          {getFieldDecorator('tenantName', {
            initialValue: tenantName,
            rules: [
              {
                required: true,
                message: '租户名称不能为空',
              },
            ],
          })(<Input placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        <Form.Item label="租户编码">
          {getFieldDecorator('tenantCode', {
            initialValue: tenantCode,
            rules: [
              {
                required: true,
                message: '租户编码不能为空',
              },
            ],
          })(<Input placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        <Form.Item label="HTTP数据源URL前缀">
          {getFieldDecorator('httpDataSourceUrlPrefix', {
            initialValue: httpDataSourceUrlPrefix,
            rules: [
              {
                required: true,
                message: 'HTTP数据源URL前缀不能为空',
              },
              {
                pattern: /^\/.*$/,
                message: 'URL前缀必须以"/"开头',
              },
            ],
          })(<Input placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        <Form.Item label="ACCESS_KEY">
          {getFieldDecorator('accessKey', {
            initialValue: accessKey,
            rules: [
              {
                required: true,
                message: 'ACCESS_KEY不能为空',
              },
            ],
          })(
            <Search
              onSearch={generateAccessKey}
              placeholder="请生成"
              readOnly
              loading={accessKeyLoading}
              enterButton={getFieldValue('accessKey') ? '重新生成' : '点击生成'}
            />
          )}
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default Form.create()(AddTenantModal);
